/*
 * PACKAGE NAME: com.jodinfo.outmirror.api.reportrepair.service
 * FILE    NAME: ReportRepairDaoImpl.java
 * COPYRIGHT: Copyright(c) © 2016 heroj Company Ltd. All Rights Reserved
 */ 
package com.jodinfo.outmirror.api.reportrepair.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.alibaba.fastjson.JSON;
import com.hero.common.web.excel.util.ExcelExport;
import com.hero.core.constant.SysConstant;
import com.hero.core.entity.PageResult;
import com.hero.core.entity.ResponseEntity;
import com.hero.core.exception.AbstractGenericException;
import com.hero.core.util.DateUtils;
import com.hero.core.util.StringUtils;
import com.hero.core.util.ValidationUtil;
import com.jodinfo.outmirror.api.ReportConstant;
import com.jodinfo.outmirror.api.Dymcform.service.DymcformQueryService;
import com.jodinfo.outmirror.api.org.entity.OrgEntity;
import com.jodinfo.outmirror.api.org.service.OrgQueryService;
import com.jodinfo.outmirror.api.purbarcode.entity.PurBarcodeEntity;
import com.jodinfo.outmirror.api.purbarcode.service.PurBarcodeQueryService;
import com.jodinfo.outmirror.api.reportinventoryanalyze.service.OfficeEntity;
import com.jodinfo.outmirror.api.reportrepair.entity.ReportRepairEntity;
import com.jodinfo.outmirror.api.reportrepairbarcode.entity.ReportRepairBarcodeEntity;
import com.jodinfo.outmirror.api.workflow.entity.UserTask;
import com.jodinfo.outmirror.api.workflow.service.ActivitiTaskQueryService;
import com.taobao.ad.easyschedule.dataobject.JobData;
import com.taobao.ad.easyschedule.dataobject.JobResult;

@Service(value="reportRepairBizService")
public class ReportRepairBizServiceImpl  implements ReportRepairBizService  {
    private static final Logger logger = LoggerFactory.getLogger(ReportRepairBizServiceImpl.class);
 	
 	@Resource(name="reportRepairDmlService")
	private ReportRepairDmlService ReportRepairDmlService;
	@Resource(name="reportRepairQueryService")
	private ReportRepairQueryService ReportRepairQueryService;
	@Resource(name="reportRepairTransactionService")
	private ReportRepairTransactionService reportRepairTransactionService;
	
	@Resource(name="dymcformQueryService")
	private DymcformQueryService dymcformQueryService;
	@Resource(name="activitiTaskQueryService")
	private ActivitiTaskQueryService activitiTaskQueryService;
	@Resource(name="orgQueryService")
	private OrgQueryService orgQueryService;
	@Resource(name="purBarcodeQueryService")
	private PurBarcodeQueryService purBarcodeQueryService;
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairBizService#addReportRepair(ReportRepairEntity ReportRepairEntity)
	 * @param ReportRepairEntity ReportRepairEntity
	 * @return int
	 */
	public ResponseEntity addReportRepair(ReportRepairEntity ReportRepairEntity) {
			ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
			  	 int i =  ReportRepairDmlService.addReportRepair(ReportRepairEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairBizService#updateReportRepair(ReportRepairEntity ReportRepairEntity)
	 * @param ReportRepairEntity ReportRepairEntity
	 * @return ResponseEntity
	 */
	public ResponseEntity updateReportRepair(ReportRepairEntity ReportRepairEntity) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = ReportRepairDmlService.updateReportRepair(ReportRepairEntity);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairBizService#queryAllReportRepair(ReportRepairEntity ReportRepairEntity)
	 * @param ReportRepairEntity ReportRepairEntity
	 * @return String
	 */
	public String queryAllReportRepair(ReportRepairEntity ReportRepairEntity) {
		return JSON.toJSONString(convertCodeToName(ReportRepairQueryService.queryAllReportRepair(ReportRepairEntity)));
	} 
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairBizService#queryAllReportRepair(ReportRepairEntity ReportRepairEntity)
	 * @param ReportRepairEntity ReportRepairEntity
	 * @return PageResult
	 */
	public String queryListForPageReportRepair(ReportRepairEntity ReportRepairEntity) {
		return new PageResult( convertCodeToName(ReportRepairQueryService.queryListForPageReportRepair(ReportRepairEntity)), ReportRepairQueryService.queryCountReportRepair(ReportRepairEntity)).toString();
	} 
	/** 
	 * 
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairQueryService#queryById(ReportRepairEntity ReportRepairEntity)
	 * @param BigInteger id
	 * @return
	 */
	public ReportRepairEntity queryById(BigInteger id) {
		return ReportRepairQueryService.queryById(id);
	}
	
	public void exportReportRepair(ReportRepairEntity ReportRepairEntity, HttpServletResponse response) {
		List<ReportRepairEntity> exportList = null;
		String ids = ReportRepairEntity.getIds();
		if (ValidationUtil.isNullOrEmptyString(ids)) {
			exportList =ReportRepairQueryService.queryAllReportRepair(ReportRepairEntity);
		} else {
			String[] idArray = ids.split(",");
			List<BigInteger> idList = new ArrayList<BigInteger>();
			for(String id : idArray) {
				idList.add(new BigInteger(id));
			}
			exportList = ReportRepairQueryService.queryByIds(idList);
			// 将字典中的code转换为name
		   //convertCodeToName(exportList);
		}
		convertCodeToName(exportList);
		ExcelExport.exportExcel(exportList, "ReportRepairEntityExcel", "ReportRepairEntity信息", response);
	}
	
	private List<ReportRepairEntity> convertCodeToName(List<ReportRepairEntity> exportList) {
		if(!CollectionUtils.isEmpty(exportList)){
			for(ReportRepairEntity e: exportList){
				if("0".equals(e.getStatusNumId())){
					e.setStatusNumName("确认");
				}else if("1".equals(e.getStatusNumId())){
					e.setStatusNumName("入库");
				}else if("2".equals(e.getStatusNumId())){
					e.setStatusNumName("出库");
				}
			}
		}
		
		return exportList;
	}
	/** 
	 * 批量删除 数据处理
	 * @author weiwei
	 * @date 2016年12月30日 上午9:15:36
	 * @see com.jodinfo.outmirror.implementation.reportrepair.ReportRepairQueryService#queryById(ReportRepairEntity ReportRepairEntity)
	 * @param BigInteger id
	 * @return
	 */
	public ResponseEntity batchDelReportRepair(ReportRepairEntity ReportRepairEntity) {
		String ids = ReportRepairEntity.getIds();
		String[] idArray = ids.split(",");
		List<ReportRepairEntity> ReportRepairEntityList = new ArrayList<ReportRepairEntity>();
		for(String id : idArray) {
			ReportRepairEntity ReportRepairModel = new ReportRepairEntity();
			ReportRepairModel.setId(new BigInteger(id));
//			ReportRepairModel.setLastUpdateUsrName(UserContext.getUser().getName());
//			ReportRepairModel.setLastUpdateTime(DateUtils.getCurrentTime());
//			ReportRepairModel.setIsDel(SysConstant.IS_DEL_Y);
			ReportRepairModel.setUpdateTime(DateUtils.getCurrentTime());
			ReportRepairEntityList.add(ReportRepairModel);
		}
		return batchUpdateReportRepair(ReportRepairEntityList);
	}
	
	/**
	 * 执行批量删除操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:40:31
	 * @param ReportRepairList
	 * @return
	 */
	public ResponseEntity batchUpdateReportRepair(List<ReportRepairEntity> ReportRepairList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
			try{
				int i = ReportRepairDmlService.batchUpdateReportRepair(ReportRepairList);
				 rs.setMessage(i+"条记录操作成功");
			 }catch(AbstractGenericException e){
				logger.error(e.getFullMessage());
				rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
			}catch(Exception e){
				String errorMessage = StringUtils.toString(e);
				logger.error(errorMessage);
				rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
			}
		return rs;
	}
	
	/**
	 * 
	 * @author weiwei
	 * @date 2017年3月13日 上午10:24:53
	 * @see  com.jodinfo.outmirror.implementation.reportrepair.ReportRepairQueryService#queryById(ReportRepairEntity ReportRepairEntity)
	 * @param map
	 * @param excelimportcontext
	 * @param s
	 * @return
	 * @throws Exception
	 */
	/*public List<BigInteger> insertData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext, String s) throws Exception {
		String usrName = UserContext.getUser().getName();//数据创建人
		String creatTime = DateUtils.getCurrentTime();
		List<ReportRepairEntity> ReportRepairList = validateReportRepairData(map, excelimportcontext,usrName,creatTime);
		if (!excelimportcontext.hasError() && ReportRepairList.size() > 0) {
			batchAddReportRepair(ReportRepairList);
		}
		return null;
	}*/
	
	/**
	 * 
	 * TODO 验证数据 处理业务数据
	 * @author weiwei
	 * @date 2017年3月13日 上午9:33:30
	 * @see  com.jodinfo.outmirror.implementation.reportrepair.ReportRepairQueryService#queryById(ReportRepairEntity ReportRepairEntity)
	 * @param ReportRepairList
	 * @return
	 */
	/*public List<ReportRepairEntity> validateReportRepairData(Map<Integer, List<Object>> map,ExcelImportContext excelimportcontext,String usrName,String creatTime) {
		ExcelImportContext.DataError errorMsg = null;
		List<ReportRepairEntity> ReportRepairList = new ArrayList<ReportRepairEntity>();
		for (Map.Entry<Integer, List<Object>> entity : map.entrySet()) {
			List<Object> excelModelList = entity.getValue();
			if (ValidationUtil.isNullOrEmptyCollection(excelModelList)) {
		//		errorMsg = excelimportcontext.new DataError(InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET,
		//				"导入数据为空！",InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
		//		excelimportcontext.push(errorMsg);
			}else{
				//TODO 验证对应数据
				for (int i =0;i<excelModelList.size();i++) {
					ReportRepairEntity ReportRepairModel = (ReportRepairEntity) excelModelList.get(i);
	 				if (checkDataByEntityModel(shShopModel, excelimportcontext, i)) {
						break;
					}
					//TODO 实体对象加入对应参数值 
					ReportRepairModel = setEntityData(ReportRepairModel,usrName, creatTime);
					ReportRepairList.add(ReportRepairModel);
				}
			}
		}
		return ReportRepairList;
	}*/
	
	/**
	 * 
	 * 单个导入实体数据校验 有错误返回true
	 * @author weiwei
	 * @date 2017年3月28日 下午3:59:17
	 * @param eqEquipmentModel
	 * @param excelimportcontext
	 * @param i
	 * @return
	 */
	/*public boolean checkDataByEntityModel(ReportRepairEntity ReportRepairModel,ExcelImportContext excelimportcontext,int i) {
		if (checkSingleData(excelimportcontext, ReportRepairModel.getIsDel, i+2,"错误信息") 
			//	|| checkSingleData(excelimportcontext, ReportRepairModel.getEquipmentColor(), i+2, "颜色为空！")
			//	||checkSingleData(excelimportcontext, ReportRepairModel.getEquipmentModel(), i+2, "型号为空！")
				) {
			return true;
		}else{
			return false;
		}
	}*/
	
	/**
	 * 
	 * 设置报错信息
	 * @author weiwei
	 * @date 2017年3月22日 下午5:17:37
	 * @param excelimportcontext
	 * @param rowNumId
	 * @param errorMessage
	 * @param sheetNumId 现在只有一个sheet 就不传值 默认值即可
	 */
	/*public boolean checkSingleData(ExcelImportContext excelimportcontext,String checkVal,int rowNumId,String errorMessage) {
		boolean flag = false;
		ExcelImportContext.DataError errorMsg = null;
		if (ValidationUtil.isNullOrEmptyString(checkVal)) {
			errorMsg = excelimportcontext.new DataError(rowNumId,errorMessage,InventoryConstantUtil.IMPORT_DATA_ERROR_TYPE_NOT_SHEET);
			excelimportcontext.push(errorMsg);
			flag = true;
		}
		return flag;
	}*/
	
	/**
	 * 
	 * 导入单个实体添加统一导入人及导入时间
	 * @author zhuxiaoliu
	 * @date 2017年3月28日 下午4:05:15
	 * @param eqEquipmentModel
	 * @param usrName
	 * @param creatTime
	 * @return
	 */
	/*public ReportRepairEntity setEntityData(ReportRepairEntity ReportRepairModel,String usrName,String creatTime) {
		
		//ReportRepairModel.setEquipmentId(InventoryConstantUtil.EQ_EQUIPMENT_SEQUENCE);
		ReportRepairModel.setCreateTime(creatTime);
		ReportRepairModel.setCreateUsrName(usrName);
		ReportRepairModel.setLastUpdateUsrName(usrName);
		ReportRepairModel.setLastUpdateTime(creatTime);
		ReportRepairModel.setIsDel(SysConstant.IS_DEL_N);
		return ReportRepairModel;
	}*/
	
	
	/**
	 * 
	 * 执行批插入操作
	 * @author weiwei
	 * @date 2017年3月13日 上午11:37:14
	 * @param {moduleName}List
	 * @return
	 */
	public ResponseEntity batchAddReportRepair(List<ReportRepairEntity> ReportRepairList) {
		 ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS, "操作成功");
		try{
			int i = ReportRepairDmlService.batchAddReportRepair(ReportRepairList);
			 rs.setMessage(i+"条记录插入操作成功");
		 }catch(AbstractGenericException e){
			logger.error(e.getFullMessage());
			rs.setStatus(SysConstant.FAIL).setMessage(e.getFullMessage());
		}catch(Exception e){
			String errorMessage = StringUtils.toString(e);
			logger.error(errorMessage);
			rs.setStatus(SysConstant.FAIL).setMessage(errorMessage);
		}
		return rs;
	}
	
	public JobResult execute(JobData jobData) throws Exception {
		ResponseEntity rs = scanFinishedForm(null);
		JobResult jobResult = JobResult.succcessResult();
		jobResult.setResultMsg(rs.getMessage());
		return jobResult;
	}
//	private Map<String, List<Map<String,Object>>> getOrgMap(
//			List<OrgEntity> orgList) {
//		Map<String,List<Map<String,Object>>> map = new HashMap<String,List<Map<String,Object>>>();
//		for(OrgEntity orgEntity: orgList){
//			map.put(orgEntity.getOrgId(), new ArrayList<Map<String,Object>>());
//		}
//		return map;
//	}
	/**
	 * 扫描已经完成的维修单
	 * @author cao.weiwei
	 * @date 2017年6月29日 上午10:54:29
	 * @return
	 */
	public ResponseEntity scanFinishedForm(String date){
		ResponseEntity rs = new ResponseEntity(SysConstant.SUCCESS,"操作成功");
		try{
			
		UserTask userTask = new UserTask();
		userTask.setWorkflowId(ReportConstant.WORKFLOWID_EQUIPMENT_SERVICE);
		List<UserTask> taskList = new ArrayList<UserTask>();
		if(StringUtils.isEmpty(date)){ // 查询昨日
			taskList = activitiTaskQueryService.queryFinishTaskListByProcess(userTask);
		}else{ // 查询date当日
			taskList = activitiTaskQueryService.queryFinishTaskListByProcessDay(userTask,date);
		}
		
		List<ReportRepairEntity> reportRepairEntityList = new ArrayList<ReportRepairEntity>();
		List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList = new ArrayList<ReportRepairBarcodeEntity>();
		for(UserTask task: taskList){
			List<Map<String,Object>> mainTableList = dymcformQueryService.queryList(buildQueryRepairTableSql(task.getBusinessNo()));
			if(!CollectionUtils.isEmpty(mainTableList)){
//				buildCalEquipmentList(reportRepairEntityList, reportRepairBarcodeEntityList,
//						task, mainTable);
//				buildServiceEquipmentList(reportRepairEntityList, reportRepairBarcodeEntityList,
//						task, mainTable);
//				buildNewEquipmentList(reportRepairEntityList, reportRepairBarcodeEntityList,
//						task, mainTable);
			
				buildServiceEquipmentList2(reportRepairEntityList, reportRepairBarcodeEntityList,
						task, mainTableList.get(0),"1","2"); // statusNumId 1 ,attribute 2 维修
				buildServiceEquipmentList2(reportRepairEntityList, reportRepairBarcodeEntityList,
						task, mainTableList.get(0),"1","3"); // statusNumId 1 ,attribute 3 报废
				buildServiceEquipmentList2(reportRepairEntityList, reportRepairBarcodeEntityList,
						task, mainTableList.get(0),"1","1"); // statusNumId 1 ,attribute blank 安装  8月4日更新blank状态为1
			}
		}
		if(!StringUtils.isEmpty(date)){ 
			setUpdateTimeOneday(date, reportRepairEntityList,
					reportRepairBarcodeEntityList);
		}else{
			setUpdateTime(reportRepairEntityList,reportRepairBarcodeEntityList);
		}
		reportRepairTransactionService.addReportRepairAndBarcode(reportRepairEntityList,reportRepairBarcodeEntityList);
		
		}catch(Exception e){
			logger.debug(StringUtils.toString(e));
			rs.setMessage(StringUtils.toString(e));
			rs.setStatus(SysConstant.FAIL);
		}
		return rs;
		
	}
	
	private void setUpdateTime(List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList) {
		String todayDate = DateUtils.getCurrentTime().substring(0,10);
		Date yesterD = DateUtils.getDatePlusDay(DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, todayDate), -1);
		String yester =  DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, yesterD);
		for(ReportRepairEntity r : reportRepairEntityList){
			r.setUpdateTime(yester);
		}
		for(ReportRepairBarcodeEntity r: reportRepairBarcodeEntityList){
			r.setUpdateTime(yester);
		}
	}
	/**
	 * 设置报表更新日期
	 * @author cao.weiwei
	 * @date 2017年8月9日 上午11:49:34
	 * @param date
	 * @param reportRepairEntityList
	 * @param reportRepairBarcodeEntityList
	 */
	private void setUpdateTimeOneday(String date,
			List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList) {
		Date theDate = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, date);
		String upd = DateUtils.DateToString(DateUtils.TIMEPATTERN_YYYYMMDD, theDate);
		for(ReportRepairEntity r: reportRepairEntityList){
			r.setUpdateTime(upd);
		}
		for(ReportRepairBarcodeEntity r: reportRepairBarcodeEntityList){
			r.setUpdateTime(upd);
		}
	}
/*	
	private ReportRepairEntity buildReportRepairFromPurbarcode(PurBarcodeEntity purBarcodeEntity ){
		ReportRepairEntity rre = new ReportRepairEntity();
		rre.setEquipmentId(purBarcodeEntity.getEquipmentId());
		rre.setEquipmentName(purBarcodeEntity.getEquipmentName());
		rre.setEquipmentTypeId(purBarcodeEntity.getEquipmentType());
		rre.setEquipmentTypeName(purBarcodeEntity.getEquipmentTypeName());
		return rre;
	}*/
/*	private void buildNewEquipmentList(List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList,
			UserTask task, Map<String, Object> mainTable) {
		List<Map<String,Object>> newTableList = dymcformQueryService.queryList(buildQueryRepairSubTableSql(mainTable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SERVICE_NEW));
		if(!CollectionUtils.isEmpty(newTableList)){
			for(Map<String,Object> item: newTableList){
				ReportRepairEntity reportRepairEntity = buildReportRepairEntity(task,
						mainTable, item);
				reportRepairEntity.setStatus("1"); //新设备
				reportRepairEntity.setUpdateTime(DateUtils.getCurrentTime().substring(0, 10));
				reportRepairEntity.setFinishDate(task.getEndTime());
				reportRepairEntityList.add(reportRepairEntity);
				PurBarcodeEntity purBarcodeEntity = new PurBarcodeEntity();
				purBarcodeEntity.setBusinessKey(mainTable.get("WO_NO")+"");
				purBarcodeEntity.setStorageNumId(mainTable.get("STORAGE_ID")+"");
				purBarcodeEntity.setEquipmentType(item.get("EQ_TYPE_ID")+"");
				purBarcodeEntity.setStatusNumId("2");
				
				List<PurBarcodeEntity> purBarcodeEntityList = purBarcodeQueryService.queryAllPurBarcode(purBarcodeEntity);
				buildBarcodeEntity(reportRepairBarcodeEntityList, purBarcodeEntityList);
			}
		}
	}
	private void buildServiceEquipmentList(List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList,
			UserTask task, Map<String, Object> mainTable) {
		List<Map<String,Object>> serviceTableList = dymcformQueryService.queryList(buildQueryRepairSubTableSql(mainTable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SERVICE_SERVICE));
		if(!CollectionUtils.isEmpty(serviceTableList)){
			for(Map<String,Object> item: serviceTableList){
				ReportRepairEntity reportRepairEntity = buildReportRepairEntity(task,
						mainTable, item);
				reportRepairEntity.setStatus("2"); //报废设备
				reportRepairEntity.setUpdateTime(DateUtils.getCurrentTime().substring(0, 10));
				reportRepairEntity.setFinishDate(task.getEndTime());
				reportRepairEntityList.add(reportRepairEntity);
				PurBarcodeEntity purBarcodeEntity = new PurBarcodeEntity();
				purBarcodeEntity.setBusinessKey(mainTable.get("WO_NO")+"");
				purBarcodeEntity.setEquipmentType(item.get("EQ_TYPE_ID")+"");
				purBarcodeEntity.setStatusNumId("1");
				purBarcodeEntity.setAttributeNumId("2");
				List<PurBarcodeEntity> purBarcodeEntityList = purBarcodeQueryService.queryAllPurBarcode(purBarcodeEntity);
				buildBarcodeEntity(reportRepairBarcodeEntityList, purBarcodeEntityList);
			}
		}
	}*/
	private void buildServiceEquipmentList2(List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList,
			UserTask task, Map<String, Object> mainTable,String statusNumId,String attributeNumId) {
		PurBarcodeEntity purbarcodeEntity = new PurBarcodeEntity();
		purbarcodeEntity.setBusinessKey(task.getBusinessNo());
		purbarcodeEntity.setStatusNumId(statusNumId);	// 入库
		if("blank".equals(attributeNumId)){
			purbarcodeEntity.setAttributeNumIdBlank("blank"); // 瑕疵
		}else{
			purbarcodeEntity.setAttributeNumId(attributeNumId); // 瑕疵
		}
		
		List<PurBarcodeEntity> purbarcodeEntityList = purBarcodeQueryService.queryGroupByEqId(purbarcodeEntity);
		if(!CollectionUtils.isEmpty(purbarcodeEntityList)){
			for(PurBarcodeEntity item: purbarcodeEntityList){
				// 组建报表实体
				ReportRepairEntity reportRepairEntity = buildReportRepairEntity2(task,
						mainTable, item);
				reportRepairEntityList.add(reportRepairEntity);
				// 查询条码
				PurBarcodeEntity purBarcodeEntity = new PurBarcodeEntity();
				purBarcodeEntity.setBusinessKey(item.getBusinessKey());
				purBarcodeEntity.setEquipmentType(item.getEquipmentType());
				purBarcodeEntity.setEquipmentId(item.getEquipmentId());
				purBarcodeEntity.setStatusNumId(item.getStatusNumId());
				purBarcodeEntity.setAttributeNumId(item.getAttributeNumId());
				List<PurBarcodeEntity> purBarcodeEntityList = purBarcodeQueryService.queryAllPurBarcode(purBarcodeEntity);
				buildBarcodeEntity(reportRepairBarcodeEntityList, purBarcodeEntityList);
			}
		}
	}
	
	private void buildCalEquipmentList(List<ReportRepairEntity> reportRepairEntityList,
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList,
			UserTask task, Map<String, Object> mainTable) {
		List<Map<String,Object>> callTableList = dymcformQueryService.queryList(buildQueryRepairSubTableSql(mainTable.get("ID").toString(),ReportConstant.DYMCFORM_SUBTABLE_EQUIPMENT_SERVICE_CALL));
		if(!CollectionUtils.isEmpty(callTableList)){
			for(Map<String,Object> item: callTableList){
				ReportRepairEntity reportRepairEntity = buildReportRepairEntity(task,mainTable, item);
				reportRepairEntity.setStatus("3"); //报废设备
				reportRepairEntity.setUpdateTime(DateUtils.getCurrentTime().substring(0, 10));
				reportRepairEntity.setFinishDate(task.getEndTime());
				reportRepairEntityList.add(reportRepairEntity);
				PurBarcodeEntity purBarcodeEntity = new PurBarcodeEntity();
				purBarcodeEntity.setBusinessKey(item.get("WO_NO")+"");
				purBarcodeEntity.setEquipmentType(item.get("EQ_TYPE_ID")+"");
				purBarcodeEntity.setStatusNumId("1");
				purBarcodeEntity.setAttributeNumId("3");
				List<PurBarcodeEntity> purBarcodeEntityList = purBarcodeQueryService.queryAllPurBarcode(purBarcodeEntity);
				buildBarcodeEntity(reportRepairBarcodeEntityList, purBarcodeEntityList);
			}
		}
	}
	/**
	 * 组建条码表对象
	 * @author cao.weiwei
	 * @date 2017年7月3日 上午11:50:03
	 * @param reportRepairBarcodeEntityList
	 * @param item
	 */
	private void buildBarcodeEntity(
			List<ReportRepairBarcodeEntity> reportRepairBarcodeEntityList,
			List<PurBarcodeEntity> purBarcodeEntityList) {
		
		for(PurBarcodeEntity code: purBarcodeEntityList){
			// 组建条码表实体
			ReportRepairBarcodeEntity reportRepairBarcodeEntity = new ReportRepairBarcodeEntity();
			reportRepairBarcodeEntity.setAccessType(code.getStatusNumId());
			reportRepairBarcodeEntity.setBusinessId(code.getBusinessKey());
			reportRepairBarcodeEntity.setEquipmentBarcode(code.getEquipmentBarcode());
			reportRepairBarcodeEntity.setEquipmentTypeId(code.getEquipmentType());
			reportRepairBarcodeEntity.setEquipmentTypeName(code.getEquipmentTypeName());
			reportRepairBarcodeEntity.setEquipmentId(code.getEquipmentId());
			reportRepairBarcodeEntity.setEquipmentName(code.getEquipmentName());
			reportRepairBarcodeEntity.setStatusNumId(code.getStatusNumId());
			reportRepairBarcodeEntity.setAttributeNumId(code.getAttributeNumId());
			reportRepairBarcodeEntityList.add(reportRepairBarcodeEntity);
		}
	}
	
	/**
	 * 组建插入数据实体
	 * @author cao.weiwei
	 * @date 2017年6月30日 下午2:35:25
	 * @param task
	 * @param mainTable
	 * @param item
	 * @return
	 */
	private ReportRepairEntity buildReportRepairEntity(UserTask task,
			Map<String, Object> mainTable, Map<String, Object> item) {
		ReportRepairEntity reportRepairEntity = new ReportRepairEntity();
		Integer days =  getDaysBetweenDates( task.getCreateTime(),task.getEndTime());
		reportRepairEntity.setBusinessId(task.getBusinessNo());
		reportRepairEntity.setEquipmentTypeId(item.get("EQ_TYPE_ID")+"");
		reportRepairEntity.setEquipmentTypeName(item.get("EQ_TYPE_NAME")+"");
		reportRepairEntity.setQuantity(item.get("EQ_NUM")+"");
		reportRepairEntity.setCreateUser(mainTable.get("CREATER")+"");
		reportRepairEntity.setCreateUserId(mainTable.get("CREATE_USER")+"");
		reportRepairEntity.setCreateDate(mainTable.get("CREATE_TIME")+"");
		reportRepairEntity.setShopId(mainTable.get("SHOP_ID")+"");
		reportRepairEntity.setShopName(mainTable.get("SHOP_NAME")+"");
		reportRepairEntity.setStatus("已完成");
		reportRepairEntity.setDuration(days+"");
		OfficeEntity office = getBanchOrg(mainTable.get("ORG_ID")+"");
		reportRepairEntity.setBranchOrgId(office.getBranchOrgId());
		reportRepairEntity.setBranchOrgName(office.getBranchOrgName());
		reportRepairEntity.setOfficeOrgId(office.getOfficeOrgId());
		reportRepairEntity.setOfficeOrgName(office.getOfficeOrgName());
		return reportRepairEntity;
	}
	
	private ReportRepairEntity buildReportRepairEntity2(UserTask task,
			Map<String, Object> mainTable, PurBarcodeEntity item) {
		ReportRepairEntity reportRepairEntity = new ReportRepairEntity();
		Integer days =  getDaysBetweenDates( task.getCreateTime(),task.getEndTime());
		reportRepairEntity.setBusinessId(task.getBusinessNo());
		reportRepairEntity.setEquipmentTypeId(item.getEquipmentType());
		reportRepairEntity.setEquipmentTypeName(item.getEquipmentTypeName());
		reportRepairEntity.setEquipmentId(item.getEquipmentId());
		reportRepairEntity.setEquipmentName(item.getEquipmentName());
		reportRepairEntity.setQuantity(item.getQty());
		reportRepairEntity.setCreateUser(mainTable.get("CREATER")+"");
		reportRepairEntity.setCreateUserId(mainTable.get("CREATE_USER")+"");
		reportRepairEntity.setCreateDate(mainTable.get("CREATE_TIME")+"");
		reportRepairEntity.setShopId(mainTable.get("SHOP_ID")+"");
		reportRepairEntity.setShopName(mainTable.get("SHOP_NAME")+"");
		reportRepairEntity.setDuration(days+"");
		OfficeEntity office = getBanchOrg(mainTable.get("ORG_ID")+"");
		reportRepairEntity.setBranchOrgId(office.getBranchOrgId());
		reportRepairEntity.setBranchOrgName(office.getBranchOrgName());
		reportRepairEntity.setOfficeOrgId(office.getOfficeOrgId());
		reportRepairEntity.setOfficeOrgName(office.getOfficeOrgName());
//		reportRepairEntity.setStatus(item.getAttributeNumId()); //报废设备
		reportRepairEntity.setAttributeNumId(item.getAttributeNumId());
		reportRepairEntity.setStatusNumId(item.getStatusNumId());
		reportRepairEntity.setUpdateTime(DateUtils.getCurrentTime().substring(0, 10));
		reportRepairEntity.setFinishDate(task.getEndTime());
		return reportRepairEntity;
	}
	
	/**
	 * 组建查询维修表数据
	 * @author cao.weiwei
	 * @date 2017年6月30日 上午9:42:57
	 * @param wo_no
	 * @return
	 */
	private String buildQueryRepairTableSql(String wo_no){
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT ID,WO_NO,SHOP_ID,SHOP_NAME,ORG_ID,CREATE_USER,CREATER,CREATE_TIME ");
		sb.append("FROM ").append(ReportConstant.DYMCFORM_TABLE_EQUIPMENT_SERVICE).append(" where ");
		sb.append("WO_NO ='").append(wo_no).append("'  and CHECK_RESULT='1' and CONFIRM_RESULT='1' ");
		sb.append(";");
		return sb.toString();
	}
	
	/**
	 * 组建查询维修子表数据
	 * @author cao.weiwei
	 * @date 2017年6月30日 上午9:43:28
	 * @param mainTableId
	 * @param subTableName
	 * @return
	 */
	private String buildQueryRepairSubTableSql(String mainTableId,String subTableName){
		StringBuffer sb = new StringBuffer();
		sb.append(" SELECT EQ_TYPE_ID,EQ_TYPE_NAME,EQ_NUM ");
		sb.append(" FROM ").append(subTableName);
		sb.append(" WHERE ");
		sb.append(" MAIN_TABLE_ID ='").append(mainTableId).append("'");
		sb.append(" AND IS_DEL = '0';");
		return sb.toString();
	}
	
	
	/**
	 * 获取时间间隔
	 * @author cao.weiwei
	 * @date 2017年6月30日 上午11:20:13
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	 public static int getDaysBetweenDates(String startDate, String endDate){
		  long time1 = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, startDate).getTime();
		  long time2 = DateUtils.stringToDate(DateUtils.TIMEPATTERN_YYYYMMDD, endDate).getTime();
		  long len = Math.abs(time2-time1);
		  Double days = Math.ceil(len *1 /(1000*60*60*24));
		if(days <1){
			return 1;
		}else{
			return days.intValue();
		}
	  }
	 
	 public  OfficeEntity getBanchOrg(String orgId){
			OfficeEntity office = new OfficeEntity();
			 Map<String,String> map = new HashMap<String,String>();
			 OrgEntity orgEntity = new OrgEntity();
			 List<OrgEntity> orgList =  orgQueryService.queryAllOrg(orgEntity);
			 for(OrgEntity o: orgList){
				 if(o.getOrgId().equals(orgId)){
					 if("0".equals(o.getOrgType())){
						 office.setBranchOrgId(o.getOrgId());
						 office.setBranchOrgName(o.getOrgName());
						 office.setOfficeOrgId(o.getOrgId());
						 office.setOfficeOrgName(o.getOrgName());
					 }else if("1".equals(o.getOrgType())){
						 office.setBranchOrgId(o.getOrgId());
						 office.setBranchOrgName(o.getOrgName());
						 office.setOfficeOrgId(o.getOrgId());
						 office.setOfficeOrgName(o.getOrgName());
					 }else if("2".equals(o.getOrgType())){
						 office.setBranchOrgId(o.getParentOrgId());
						 office.setBranchOrgName(o.getParentOrgName());
						 office.setOfficeOrgId(o.getOrgId());
						 office.setOfficeOrgName(o.getOrgName());
					 }
				 }
				 
			 }
			return office; 
		 }
	public ResponseEntity testTask(String date) {
		if(StringUtils.isEmpty(date)){
			return scanFinishedForm(null);
		}else{
			return scanFinishedForm(date);
		}
	}
}

